package com.lc.cn.managersys.service.SysMaintain;


import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import com.lc.cn.managersys.dao.SysMaintain.CategoryMaintainDao;
import com.lc.cn.managersys.model.CategoryForm;

/**
 * service CategoryMaintain
 *
 */
@Service
public class CategoryMaintainService {

	@Autowired
	private CategoryMaintainDao dao = null;
	
	public String listHeader(Integer prioId) {
		CategoryForm vechile = dao.getCategory(prioId);
		StringBuilder sb = new StringBuilder();
		sb.append("[{\"id\":");
		sb.append(vechile.getId());
		sb.append(",\"text\":\"");
		sb.append(vechile.getCategoryName());
		sb.append("\",\"attributes\":");
		sb.append(vechile.getCategoryKind());
		
		String children = dao.listCategory(prioId).replaceAll("hasChildren_", "");
		if (!children.equals("")) {
			sb.append(",\"children\":");
			sb.append(children);
		}
		
		sb.append("}]");
		return sb.toString();
	}
	
	public CategoryForm getCategory(Integer categoryId) {
		return dao.getCategory(categoryId);
	}
	
	public void deleteCategory(Integer categoryId) {
		List<Integer> ids = getIdsFromTree(categoryId);
		//TODO 属性删除还有问题
	}
	
	private List<Integer> getIdsFromTree(Integer categoryId) {
		List<Integer> list = new ArrayList<Integer>();
		List<Integer> ids = dao.getCategoryIds(categoryId);
		list.addAll(ids);
		for (Integer id : ids) {
			list.addAll(getIdsFromTree(id));
		}
		
		return list;
	}
	
	public void updateCategory(Integer categoryId, String categoryName, String categoryDesc) {
		dao.updateCategory(categoryId, categoryName, categoryDesc);
	}
	
	public long insertCategory(int preId, String categoryName, String categoryDesc, Integer categoryKind) {
		return dao.insertCategory(preId, categoryName, categoryDesc, categoryKind);
	}
	
	public List<CategoryForm> listVechileSeries() {
		return dao.listVechileSeries();
	}
	
	public static void main(String[] args) {
		AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(
				"classpath*:applicationContext.xml");
		CategoryMaintainService service = (CategoryMaintainService) ctx
				.getBean("categoryMaintainService");
		// System.out.println(dao.listCategory(0).replaceAll("hasChildren_",
		// ""));
		//
		// System.out.println(dao.getCategory(0));
		// System.out.println("hasChildren_[{aaaa".indexOf("hasChildren_") >=
		// 0);

		service.listHeader(1);
		
		List<Integer> list = service.getIdsFromTree(0);
		for (Integer id : list) {
			System.out.println(id);
		}

	}
	
}
